<template>
    <div>
      <div>
        <div style="margin-bottom: 20px">
          <Col span="5"><Input style="width: 90%;" placeholder="名称" v-model="name"/></Col>
          <Button type="info"><Icon type="md-search"/>搜索</Button>
          <Button type="info"  style="margin-left: 10px" @click="addPlace"><Icon type="md-add"/>添加</Button>
        </div>
        <template>
          <Table border :columns="columns" :data="data">
            <template slot-scope="{ row }" slot="merchant_type">
<!--              {{row.merchant_type}}-->
              <span v-show="row.merchant_type==='1'">银行</span>
              <span v-show="row.merchant_type==='2'">事业单位</span>
              <span v-show="row.merchant_type==='3'">商户</span>
              <span v-show="row.merchant_type==='4'">公司</span>
              <span v-show="row.merchant_type==='5'">公园</span>
              <span v-show="row.merchant_type==='6'">广场</span>
              <span v-show="row.merchant_type==='7'">医院</span>
            </template>
            <template slot-scope="{ row, index }" slot="action">
              <Button type="primary" size="small" style="margin-right: 5px" @click="updatePlace(row)">编辑</Button>
              <Button type="error" size="small" style="margin-right: 5px" @click="deletePlace(row)">删除</Button>
            </template>
          </Table>
        </template>
      </div>
      <Modal v-model="modal" title="场所" width="1000" @on-ok="savePlace">
        <Form :model="placeInfo">

          <Row class="bench_search">
            <Col align="right" style="padding-top: 8px;" span="3" >
              <span style="color: red">*</span>
              名称：</Col>
            <Col span="8">
              <Input v-model="placeInfo.name"></Input>
            </Col>
            <Col align="right" style="padding-top: 8px;" span="4">场所负责人：</Col>
            <Col span="8">
              <Input v-model="placeInfo.place_fzr"></Input>
            </Col>
          </Row>
          <Row class="bench_search">
            <Col align="right" span="3" style="padding-top: 8px">场所负责人电话：</Col>
            <Col span="8">
              <Input v-model="placeInfo.place_fzr_phone"></Input>
            </Col>
            <Col align="right" span="4" style="padding-top: 8px">场所地址：</Col>
            <Col span="8">
              <Input v-model="placeInfo.place_address"></Input>
            </Col>
          </Row>
          <Row class="bench_search">
            <Col align="right" span="3" style="padding-top: 8px">场所营业开始时间：</Col>
            <Col span="8">
              <TimePicker style="width: 320px" v-model="placeInfo.place_time_begin"></TimePicker>
            </Col>
            <Col align="right" span="4" style="padding-top: 8px">场所营业结束时间：</Col>
            <Col span="8">
              <TimePicker style="width: 320px" v-model="placeInfo.place_time_end"></TimePicker>
            </Col>
          </Row>
          <Row class="bench_search">
            <Col align="right" span="3" style="padding-top: 8px">场所统一信用代码：</Col>
            <Col span="8">
              <Input v-model="placeInfo.place_tyshxydm"></Input>
            </Col>
            <Col align="right" span="4" style="padding-top: 8px">场所成立时间：</Col>
            <Col span="8">
              <DatePicker style="width: 320px" type="date" v-model="placeInfo.place_cl_time"></DatePicker>
            </Col>
          </Row>
          <Row class="bench_search">
            <Col align="right" span="3" style="padding-top: 8px">场所描述：</Col>
            <Col span="8">
              <Input v-model="placeInfo.place_remarks"></Input>
            </Col>
            <Col align="right" span="4" style="padding-top: 8px">场所面积：</Col>
            <Col span="6">
              <Input v-model="placeInfo.place_area"></Input>
            </Col>
            <Col align="center" span="2" style="padding-top: 8px">单位：㎡</Col>
          </Row>
          <Row class="bench_search">
            <Col align="right" span="3" style="padding-top: 8px">
              <span style="color: red">*</span>
              类型：</Col>
            <Col span="8">
              <Select v-model="placeInfo.merchant_type" style="width:320px">
                <Option v-for="item in List" :value="item.id" :key="item.value">
                    {{ item.name }}
                </Option>
              </Select>
            </Col>
            <Col align="right" span="4" style="padding-top: 8px">
              <span style="color: red">*</span>
              坐标：</Col>
            <Col span="6">
              <Input v-model="placeInfo.csc_mapjson" disabled></Input>
            </Col>
            <Col span="2">
              <Button @click="pickMap">选择</Button>
            </Col>
          </Row>
          <Row class="bench_search">
            <Col align="right" span="3" style="padding-top: 8px">场所图片：</Col>
            <Col span="4">
              <Upload multiple action="http://120.27.63.37:38081/api/ac/file/fileCommonService/upLoadFiles" :before-upload="beforeUpload" :clearFiles="11">
                <Button icon="ios-cloud-upload-outline" style="margin-bottom: 20px">上传图片</Button>
              </Upload>
            </Col>
            <Col span="4"><button style="height: 30px;width: 70px;" @click="clearUploadedImage">重新上传</button></Col>
          </Row>
          <Row class="bench_search">
            <Col span="3"></Col>
            <Col span="4" v-for="item in imgList" v-bind:key="item">
              <img v-if="imgShow || imgList" :src="item" style="width: 80px;height: 80px;margin-bottom: 20px"/>
            </Col>
          </Row>

        </Form>
      </Modal>
      <Modal v-model="modalMap" fullscreen title="地图选点" @on-ok="pickMapOK">
        <div>
          <!--     地图     -->
          <el-amap vid="amap9" class="amap-demo" :zoom="zoom" :center="center" :events="events">
            <!--     地图标记     -->
            <el-amap-marker vid="index_center" :position="center"></el-amap-marker>
          </el-amap>
        </div>
        <div class="toolbar">
          <h2>当前选中坐标: [{{ lng }}, {{ lat }}] <span v-if="this.address!=''">地址:</span> {{ address }}</h2>
        </div>
      </Modal>
    </div>
</template>

<script>
import { findMerchantList, deletePlace, addPlace, date2str, findGridZYList
  // , updatePlace
} from '@/api/eventlist'
import { createUpLoadFiles, getSign } from '../../../../api/common'

export default {
  name: 'merchant',
  props: {
    pickInfo: Object
  },
  data () {
    let self = this
    return {
      upPicData: {
        fileName: 'module',
        filePath: 'grid/module'
      },
      imgList: [],
      imgShow: false,
      List: [
        // {
        //   value: '1',
        //   label: '银行'
        // },
        // {
        //   value: '2',
        //   label: '事业单位'
        // },
        // {
        //   value: '3',
        //   label: '商户'
        // },
        // {
        //   value: '4',
        //   label: '公司'
        // },
        // {
        //   value: '5',
        //   label: '公园'
        // },
        // {
        //   value: '6',
        //   label: '广场'
        // }
      ],
      name: '',
      columns: [
        {
          title: '名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '类型',
          slot: 'merchant_type',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      data: [],
      modal: false,
      placeInfo: {},
      modalMap: false,
      zoom: 16, // 缩放
      address: '',
      lng: 0,
      lat: 0,
      center: [123.4650090000, 41.6772870000],
      events: {
        click (e) {
          console.log(e)
          let { lng, lat } = e.lnglat
          console.log(lng)
          console.log(lat)
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
          self.center = [lng, lat]
        }
      }
    }
  },
  methods: {
    clearUploadedImage () {
      this.imgList = []
      this.imgShow = false
    },
    savePlace () {
      if (!this.placeInfo.name) {
        this.$Notice.error({ title: '缺少必填项', desc: '请填写必填项名称' })
        return
      }
      if (!this.placeInfo.csc_mapjson) {
        this.$Notice.error({ title: '缺少必填项', desc: '请填写必填项坐标' })
        return
      }
      if (!this.placeInfo.merchant_type) {
        this.$Notice.error({ title: '缺少必填项', desc: '请填写必填项类型' })
        return
      }
      let place_img = ''
      this.imgList.forEach(function (item) {
        if (place_img) {
          place_img = place_img + ',' + item
        } else {
          place_img = item
        }
      })
      this.placeInfo.place_img = place_img
      this.placeInfo.place_time_begin = date2str(this.placeInfo.place_time_begin)
      this.placeInfo.place_time_end = date2str(this.placeInfo.place_time_end)
      this.placeInfo.place_cl_time = date2str(this.placeInfo.place_cl_time)
      let data = {
        placeInfo: this.placeInfo,
        pickInfo: this.pickInfo
      }
      addPlace(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '保存成功', desc: ret.data.errmsg })
          this.imgList = []
          this.init()
        } else {
          this.$Notice.error({ title: '保存失败', desc: ret.data.errmsg })
        }
      })
    },
    pickMapOK () {
      let x = this.lng + ',' + this.lat
      this.placeInfo.csc_mapjson = x
    },
    pickMap () {
      this.modalMap = true
    },
    init () {
      let data = {
        id: this.pickInfo.id
      }
      findMerchantList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.data = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    addPlace () {
      this.placeInfo = {}
      this.imgShow = false
      this.modal = true
      this.imgList = []
      this.center = this.autoCenter(this.pickInfo.csc_mapjson)
    },
    updatePlace (e) {
      this.placeInfo = {}
      this.placeInfo = e
      if (e.place_img) {
        this.imgList = e.place_img.split(',')
      }
      this.modal = true
      let x = this.placeInfo.csc_mapjson.split(',')
      this.center = []
      this.center.push(x[0])
      this.center.push(x[1])
    },
    deletePlace (e) {
      deletePlace(e).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '删除成功', desc: ret.data.errmsg })
          this.init()
        } else {
          this.$Notice.error({ title: '删除失败', desc: ret.data.errmsg })
        }
      })
    },
    // 根据多边形自动取中心点
    autoCenter (map) {
      let path = JSON.parse(map)
      let total_lng = 0.0
      let total_lat = 0.0
      path.forEach(arr => {
        total_lng += arr[0]
        total_lat += arr[1]
      })
      let newlng = total_lng / path.length
      let newlat = total_lat / path.length
      let newCenter = [newlng, newlat]
      return newCenter
    },
    beforeUpload (file) {
      this.placeInfo.place_img = ''
      this.imgShow = false
      var time = new Date().getTime()
      let timeStep = time.toString()
      let that = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        let index = reader.result.indexOf('base64,') + 7
        that.upPicData.fileName = that.upPicData.fileName + timeStep + '.' + file.type.substring(6)
        that.upPicData.file = reader.result.substring(index)
        that.upPic(that.upPicData)
      }
      return false
    },
    upPic (obj) {
      var time = new Date().getTime()
      let timeStep = time.toString()
      let param = {
        filePath: obj.filePath,
        fileName: obj.fileName,
        timestamp: timeStep
      }
      getSign(param).then(res => {
        if (res.data.errcode === 0) {
          let url = res.data.data.docking_url
          let params = {
            sign: res.data.data.sign,
            timestamp: timeStep,
            filePath: obj.filePath,
            fileName: obj.fileName,
            file: obj.file
          }
          createUpLoadFiles(url, params).then(res => {
            if (res.data.errcode === 0) {
              this.placeInfo.place_img = res.data.data
              let url = res.data.data
              this.imgList.push(url)
              console.log(this.imgList)
              this.imgShow = true
            } else {
              this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
            }
          })
        } else {
          this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
        }
      })
    },
    getMerchantType () {
      findGridZYList({ type: 'p' }).then(res => {
        if (res.data.errcode === 0) {
          let data = []
          let result = res.data.data
          result.forEach(item => {
            if (item.id !== 'P0000') {
              data.push(item)
            }
          })
          this.List = data
          console.log(this.List)
        } else {
          this.$Notice.error({ title: '查询失败', desc: res.data.msg })
        }
      })
    }
  },
  mounted () {
    this.init()
    this.getMerchantType()
  }
}
</script>

<style scoped>
  .amap-demo {
    height: 600px;
  }
  /*// 表格滚动条*/
  .ivu-table-overflowX {
    overflow-x: hidden;
  }

  /*// 模态框*/
  .item1 {
    height: 42px;
    line-height: 40px;
  }

  /*// 地图*/
  .amap-page-container {
    position: relative;
    width: 100%;
    height: 88%;
  }

  /*// 地图选点预览工具栏*/
  .toolbar {
    display: block;
    text-align: center;
    height: 20px;
    margin-top: 50px;
  }
  .ml10 {
    margin-left: 10px;
  }

  .buttonGroupB{
    margin-right: 5px;
  }

  .hu_input {
    width: 40px;
    margin-right: 5px;
  }
  .bench_search {
    margin-bottom: 10px;
  }
</style>
